<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>放大镜</title>
    <style>
        .box {
            position: relative;
            float: left;
            width: 200px;
            height: 200px;
            background: url(./images/mingzuo.jpg) no-repeat;
            background-size: 100% 100%;
        }

        .show {
            display: none;
            position: relative;
            float: left;
            width: 250px;
            height: 250px;
            margin-left: 10px;
            overflow: hidden;
        }

        .show img {
            position: absolute;
            width: 1000px;
            height: 1000px;
        }

        .fdj {
            display: none;
            position: absolute;
            width: 50px;
            height: 50px;
            background-color: rgba(230, 228, 228, 0.5);
            cursor: move;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="fdj"></div>
    </div>
    <div class="show">
        <img src="./images/mingzuo.jpg" alt="">
    </div>
    <script>
        var box = document.querySelector('.box');
        var show = document.querySelector('.show');
        var fdj = document.querySelector('.fdj');
        var img = document.querySelector('img');

        box.onmouseover = function () {
            show.style.display = 'block';
            fdj.style.display = 'block';
        }
        box.onmouseout = function () {
            show.style.display = 'none';
            fdj.style.display = 'none';
        }
        box.onmousemove = function (e) {
            fdj.style.top = e.clientY - fdj.offsetHeight / 2 + 'px';
            fdj.style.left = e.clientX - fdj.offsetWidth / 2 + 'px';

            if (fdj.offsetLeft > this.offsetWidth - fdj.offsetWidth) {
                fdj.style.left = this.offsetWidth - fdj.offsetWidth + 'px';
            } else if (fdj.offsetLeft < 0) {
                fdj.style.left = 0;
            }

            if (fdj.offsetTop < 0) {
                fdj.style.top = 0;
            } else if (fdj.offsetTop > this.offsetHeight - fdj.offsetHeight) {
                fdj.style.top = this.offsetHeight - fdj.offsetHeight + 'px';
            }


            var rate = img.offsetWidth / box.offsetWidth;
            //图片随方块移动展示
            img.style.top = -rate * fdj.offsetTop + 'px';
            img.style.left = -rate * fdj.offsetLeft + 'px';
        }

    </script>
</body>

</html>